package services;

import java.util.Collection;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import repositories.CustomerRepository;
import domain.Customer;
import forms.RegisterForm;

@Service
@Transactional
public class CustomerService {

	// Managed repository

	@Autowired
	private CustomerRepository customerRepository;

	// Supporting services
	
	// Simple CRUD methods

	public Customer create() {
		return new Customer();
	}

	public void save(Customer customer) {
		Md5PasswordEncoder encoder = new Md5PasswordEncoder(); 
		Assert.notNull(customer);
		String oldPassword = customer.getUserAccount().getPassword();
		
		Customer existingCustomer = customerRepository.findCustomerByUsername(customer.getUserAccount().getUsername());
		
		Assert.isNull(existingCustomer, "register.duplicated.username");
		
		customer.getUserAccount().setPassword(encoder.encodePassword(oldPassword, null));

		customerRepository.save(customer);
	}
	
	public void addComment(Customer customer) {
		Assert.notNull(customer);
		customerRepository.save(customer);
	}
	
	// Other business methods
	
	public Customer reconstruct(RegisterForm registerForm)
	{
		Assert.isTrue(registerForm.getTerminos(),"register.commit.terms.error");
		Assert.isTrue(registerForm.getUserAccount().getPassword().equals(registerForm.getRepeatPass()),"register.password.not.match");
		Customer customer = this.create();
		customer.setCreditCard(registerForm.getCreditCard());
		customer.setUserAccount(registerForm.getUserAccount());
		customer.setEmail(registerForm.getEmail());
		customer.setName(registerForm.getName());
		customer.setSurnames(registerForm.getSurnames());
		return customer;
	}
	
	public Collection<Customer> findAll(){
		return customerRepository.findAll();
	}
	
	public Collection<Customer> findCustomerWithMorePaintings(){
		return customerRepository.findCustomerWithMorePaintings();
	}
	
	public Collection<Customer> findCustomerWithMoreComments(){
		return customerRepository.findCustomerWithMoreComments();
	}
	
}
